/*
 * @lc app=leetcode.cn id=134 lang=javascript
 *
 * [134] 加油站
 */

// @lc code=start
/**
 * @param {number[]} gas
 * @param {number[]} cost
 * @return {number}
 */
var canCompleteCircuit = function (gas, cost) {
  const len = gas.length;
  for (let i = 0; i < len; i++) {
    let oilSum = 0, index = i;
    while (oilSum + gas[index] - cost[index] >= 0) {
      oilSum += gas[index] - cost[index];
      index = (index + 1) % len;
      if (index === i) {
        return i;
      }
    }
    if (index < i) {
      return -1
    }
    i = index;
  }
  return -1;
};
// @lc code=end
